package titt.service.strategy;

import titt.TITTValues;
import titt.head.request.MethodHead;
import titt.head.request.form.FormHead;
import titt.io.IOFactory;
import titt.io.encoding.EncodingFacade;
import titt.io.reader.POSTReader;
import titt.io.socket.TITTSocket;
import titt.service.ServicePackage;
import titt.service.os.ServiceObjectServer;
import titt.service.proxy.server.ServerProxy;
import titt.type.TypedObject;
import titt.type.Types;
import titt.util.ArrayUtil;

public class RPCStrategy implements TITTStrategy {

	private EncodingFacade ef = IOFactory.createEncodingFacade();
	
	public boolean acceptsEncoding(String enc) {
		return enc.equalsIgnoreCase("titt");
	}
	
	public void invokeAndRespond(MethodHead m, ServiceObjectServer sos, ServicePackage pack) {
		String packageID = pack.getPackageID();

		TypedObject[] params = getParameters(m, pack.getTITTSocket());

		if(params == null) {
			ServerProxy.get().sync(418,packageID);
			return;
		}

		TypedObject ret;
		int status = 200;
		
		try {
			ret = sos.getMethodInvoker().call(m.getMethodName(), params);
		}
		catch(Exception e) {			
			status = 418;
			ret = new TypedObject(Types.STRING, ""+e.getMessage());

		}

		ServerProxy.get().sync(status, ret, packageID);						


	}

	private TypedObject[] getParameters(MethodHead req, TITTSocket ts) {

		TypedObject[] params = req.getParams();

		try {

			if(req.getHTTPMethod() == TITTValues.POST) {

				POSTReader pr = new POSTReader(ts, ef, new FormHead(req));
				params = ArrayUtil.combine(params, pr.readValues());

			}

		}
		catch(Exception e) {

			return null;

		}

		try {
			
			if(!ts.isClosed())
				ts.close();

		}
		catch(Exception e) {

		}

		return params;
	}


}
